package com.avocado.dispatcher.impl;

import com.avocado.actor.AbstractActor;
import com.avocado.actor.Actor;
import com.avocado.dispatcher.ActorDispatcher;
import com.avocado.util.SystemUtil;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author avocado
 * @date 2023/5/28 22:23
 */
public class ActorRandomDispatcher implements ActorDispatcher, Runnable {

    public List<Deque<Actor>> actors;

    public ActorRandomDispatcher() {
        actors = new ArrayList<>(SystemUtil.availableProcessors);
        for (int i = 0; i < SystemUtil.availableProcessors; i++) {
            actors.add(new ArrayDeque<>(100));
        }
    }

    public boolean dispatch(Actor actor) {
        // map
        int mod = (int) (actor.getId() % SystemUtil.availableProcessors);
        actors.get(mod).offer(actor);
        return true;
    }


    @Override
    public void run() {
        // todo

        for (Actor actor : actors.get(0)) {
            AbstractActor abstractActor = (AbstractActor) actor;
            abstractActor.worker();
        }
    }
}
